<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      function array2Tree(arr, pidFiled, pidValue, childFiled) {
        return arr.filter((item) => {
          item.children = arr.filter((curr) => {
            return curr[pidFiled] == item[childFiled];
          });
          return item[pidFiled] == pidValue;
        });
      }

      const flatArr = [
        { id: "01", pid: 0, name: "节点1" },
        { id: "0111", pid: "011", name: "节点1-1-1" },
        { id: "011", pid: "01", name: "节点1-1" },
        { id: "02", pid: 0, name: "节点2" },
        { id: "022", pid: "02", name: "节点2-2" },
        { id: "023", pid: "02", name: "节点2-3" },
        { id: "0222", pid: "022", name: "节点2-2-2" },
        { id: "03", pid: 0, name: "节点3" },
      ];

      console.log(array2Tree(flatArr, "pid", 0, "id"));

      function hasChildren(item) {
        return Array.isArray(item.children) && item.children.length ;
      }
      function sortByChildren(arr) {
        let hasChildrenArr = arr.filter((item) => hasChildren(item));
        let noChildrenArr = arr.filter((item) => !hasChildren(item));
        let concatArr = hasChildrenArr.concat(noChildrenArr);

        return concatArr.map((item) => {
          item.children =
            (hasChildren(item) && sortByChildren(item.children)) || [];
          return item;
        });
      }

      let arr = [
        { data: 3 },
        {
          data: 1,
          children: [
            { data: 2},
            { data: 3, children: [{ data: 2, children: [] }] },
          ],
        },
      ];

      console.log(sortByChildren(arr));
    </script>
  </body>
</html>
